package com.cql.framework.config.security.service;

import com.cql.common.constant.FoodCircleConstant;
import com.cql.common.constant.RedisConstants;
import com.cql.common.core.redis.RedisCache;
import com.cql.common.core.security.LoginUser;
import com.cql.common.exception.CustomException;
import com.cql.common.exception.user.CaptchaException;
import com.cql.common.exception.user.CaptchaExpireException;
import com.cql.common.exception.user.UserPasswordNotMatchException;
import com.cql.common.utils.MessageUtils;
import com.cql.framework.async.AsyncManager;
import com.cql.framework.async.factory.AsyncFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author cql
 */
@Component
public class LoginService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    /**
     * 登录验证
     *
     * @param account  用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String account, String password, String code, String uuid) {
        String verifyKey = RedisConstants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(account, FoodCircleConstant.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(account, FoodCircleConstant.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(account, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLoginInfo(account, FoodCircleConstant.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLoginInfo(account, FoodCircleConstant.LOGIN_FAIL, e.getMessage()));

                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLoginInfo(account, FoodCircleConstant.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 注册成功后直接登录
     *
     * @param account
     * @param password
     * @return
     */
    public String login(String account, String password) {
        // 1.用户验证
        Authentication authentication = null;
        try {
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(account, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                logger.info("登录用户 {} 密码错误", account);
                throw new UserPasswordNotMatchException();
            } else {
                logger.info("登录用户 {} 出现异常", e.getMessage());
                throw new CustomException(e.getMessage());
            }
        }
        logger.info("用户 {} 登录成功", account);
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }

}
